package com.ruoyi.buy.service.impl;

import com.ruoyi.buy.domain.entity.PO.*;
import com.ruoyi.buy.domain.entity.inv0011.Inv0011Data;
import com.ruoyi.buy.domain.entity.inv0012.Inv0012Data;
import com.ruoyi.buy.domain.entity.inv0014.Inv0014Data;
import com.ruoyi.buy.mapper.PO.*;
import com.ruoyi.buy.service.ICommonService;
import com.ruoyi.buy.service.IInvArriveInfoItemService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 到货单明细Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-29
 */
@Service
@Transactional
public class InvArriveInfoItemServiceImpl implements IInvArriveInfoItemService
{
    @Resource
    private InvArriveInfoItemMapper invArriveInfoItemMapper;


    @Resource
    private InvArriveInfoMapper invArriveInfoMapper;

    @Autowired
    private ICommonService commonService;

    @Resource
    private BuyPurchaseBillItemMapper buyPurchaseBillItemMapper;

    @Resource
    private BuyPurchaseBillMapper buyPurchaseBillMapper;

    @Resource
    private InvInboundBillMapper invInboundBillMapper;

    @Resource
    private InvInboundBillItemMapper invInboundBillItemMapper;

    @Resource
    private InvWarehouseInfoMapper invWarehouseInfoMapper;

    /**
     * 查询到货单明细
     * 
     * @param id 到货单明细主键
     * @return 到货单明细
     */
    @Override
    public InvArriveInfoItem selectInvArriveInfoItemById(Long id)
    {
        return invArriveInfoItemMapper.selectInvArriveInfoItemById(id);
    }

    /**
     * 查询到货单明细列表
     * 
     * @param invArriveInfoItem 到货单明细
     * @return 到货单明细
     */
    @Override
    public List<InvArriveInfoItem> selectInvArriveInfoItemList(InvArriveInfoItem invArriveInfoItem)
    {
        return invArriveInfoItemMapper.selectInvArriveInfoItemList(invArriveInfoItem);
    }

    /**
     * 新增到货单明细
     * 
     * @param invArriveInfoItem 到货单明细
     * @return 结果
     */
    @Override
    public int insertInvArriveInfoItem(InvArriveInfoItem invArriveInfoItem)
    {
        invArriveInfoItem.setCreateTime(DateUtils.getNowDate());
        return invArriveInfoItemMapper.insertInvArriveInfoItem(invArriveInfoItem);
    }

    /**
     * 修改到货单明细
     * 
     * @param invArriveInfoItem 到货单明细
     * @return 结果
     */
    @Override
    public int updateInvArriveInfoItem(InvArriveInfoItem invArriveInfoItem)
    {
        invArriveInfoItem.setUpdateTime(DateUtils.getNowDate());
        return invArriveInfoItemMapper.updateInvArriveInfoItem(invArriveInfoItem);
    }

    /**
     * 批量删除到货单明细
     * 
     * @param ids 需要删除的到货单明细主键
     * @return 结果
     */
    @Override
    public int deleteInvArriveInfoItemByIds(Long[] ids)
    {
        return invArriveInfoItemMapper.deleteInvArriveInfoItemByIds(ids);
    }

    /**
     * 删除到货单明细信息
     * 
     * @param id 到货单明细主键
     * @return 结果
     */
    @Override
    public int deleteInvArriveInfoItemById(Long id)
    {
        return invArriveInfoItemMapper.deleteInvArriveInfoItemById(id);
    }

    @Override
    public List<Inv0011Data> selectNotArrivedItem(Inv0011Data para)
    {
        return  invArriveInfoItemMapper.selectNotArrivedItem(para);
    }

    @Override
    public int arriveConfirm(List<Inv0011Data> list) throws Exception {
        if (list == null || list.isEmpty() ){
            throw new Exception("不存在需要保存的信息，请确认");
        }

        //校验数量是否存在
        List<Inv0011Data> checkList = list.stream().filter(item -> (item.getnQty() == null || item.getnQty().compareTo(BigDecimal.ZERO) == 0)
        || StringUtils.isEmpty(item.getvArriveNo())).collect(Collectors.toList());
        if (!checkList.isEmpty()){
            throw new Exception("存在编号或者到货数量未填写的数据，请确认");
        }

        //按编号分组
        Map<String,List<Inv0011Data>> map = list.stream().collect(Collectors.groupingBy(item -> item.getvArriveNo()));
        for (String key:map.keySet()){
            List<Inv0011Data> itemList = map.get(key);

           //先查这个编号在到货主表中是否存在
            InvArriveInfo invArriveInfo = new InvArriveInfo();
            invArriveInfo.setvArriveNo(key);
            List<InvArriveInfo> invArriveInfos = this.invArriveInfoMapper.selectInvArriveInfoList(invArriveInfo);
            //如果为空的话就先新增一条主表记录
            if (invArriveInfos.isEmpty()){
                invArriveInfo = new InvArriveInfo();
                invArriveInfo.setvArriveNo(key);
                invArriveInfo.setvContractNo(itemList.get(0).getvContractNo());
                invArriveInfo.setvProjectNo(itemList.get(0).getvProjectNo());
                invArriveInfo.setApplyBy(itemList.get(0).getApplyBy());
                invArriveInfo.setOprBy(commonService.getUsername());
                invArriveInfo.setArriveTime(DateUtils.getNowDate());
                invArriveInfo.setCreateTime(DateUtils.getNowDate());
                invArriveInfo.setCreateBy(commonService.getUsername());
                this.invArriveInfoMapper.insertInvArriveInfo(invArriveInfo);
            }
            //新增明细数据
            for (Inv0011Data item:itemList
                 ) {
                //先增加明细
                InvArriveInfoItem invArriveInfoItem = new InvArriveInfoItem();
                BeanUtils.copyBeanProp(invArriveInfoItem,item);
                invArriveInfoItem.setCreateTime(DateUtils.getNowDate());
                invArriveInfoItem.setCreateBy(commonService.getUsername());
                invArriveInfoItem.setOprBy(commonService.getUsername());
                invArriveInfoItem.setApplyBy(itemList.get(0).getApplyBy());
                this.invArriveInfoItemMapper.insertInvArriveInfoItem(invArriveInfoItem);

                //再修改合同表明细
                BuyPurchaseBillItem buyPurchaseBillItem = this.invArriveInfoItemMapper.selectBuyPurchaseBillItem(invArriveInfoItem);
                if (null == buyPurchaseBillItem || buyPurchaseBillItem.getId() ==null){
                    throw new Exception("未找到对应合同明细记录，请联系管理员");
                }else{
                    buyPurchaseBillItem.setnArrivedQty(buyPurchaseBillItem.getnArrivedQty() ==null ? invArriveInfoItem.getnQty() : invArriveInfoItem.getnQty().add(buyPurchaseBillItem.getnArrivedQty()));
                    this.buyPurchaseBillItemMapper.updateBuyPurchaseBillItem(buyPurchaseBillItem);
                }
            }

        }
        return 1;
    }

    @Override
    public List<Inv0012Data> selectNotInWHInfoList(Inv0012Data inv0012Data) {
        return invArriveInfoMapper.selectNotInWHInfoList(inv0012Data);
    }

    @Override
    public int executeIn(List<Inv0012Data> dataList) throws Exception {
        if (dataList.isEmpty()){
            throw new Exception("没有需要操作的数据");
        }
        for (Inv0012Data item:dataList
             ) {
            //查合同相关信息
            BuyPurchaseBill buyPurchaseBill = new BuyPurchaseBill();
            buyPurchaseBill.setvBillNo(item.getvContractNo());
            List<BuyPurchaseBill> buyPurchaseBills = this.buyPurchaseBillMapper.selectBuyPurchaseBillList(buyPurchaseBill);
            buyPurchaseBill = buyPurchaseBills.get(0);
            BuyPurchaseBillItem buyPurchaseBillItem = new BuyPurchaseBillItem();
            buyPurchaseBillItem.setnMainId(buyPurchaseBills.get(0).getId());
            List<BuyPurchaseBillItem> buyPurchaseBillItems = this.buyPurchaseBillItemMapper.selectBuyPurchaseBillItemList(buyPurchaseBillItem);

            //补全主表信息
            InvInboundBill invInboundBill = new InvInboundBill();
            String vBillNo = commonService.getNo("RK");
            invInboundBill.setvBillNo(vBillNo);
            invInboundBill.setIotype("I");
            invInboundBill.setvType("ICG");
            invInboundBill.setdExecute(DateUtils.getNowDate());
            invInboundBill.setvContractNo(buyPurchaseBill.getvBillNo());//合同号
            invInboundBill.setCreateBy(commonService.getUsername());//合同号
            invInboundBill.setCreateTime(DateUtils.getNowDate());
            invInboundBillMapper.insertInvInboundBill(invInboundBill);

            //反查主表ID
            invInboundBill.setdExecute(null);
            List<InvInboundBill> list = this.invInboundBillMapper.selectInvInboundBillList(invInboundBill);
            Long nMainId = list.get(0).getId();

            //补全子表信息
            InvInboundBillItem invInboundBillItem = new InvInboundBillItem();
            invInboundBillItem.setnMainId(nMainId);
            List<BuyPurchaseBillItem> result = buyPurchaseBillItems.stream().filter(
                    x ->  x.getvSpaName().equals(item.getvSpaName())
                    && x.getvSpaModel().equals(item.getvSpaModel())
                    && x.getvSpaBrand().equals(item.getvSpaBrand())
            ).collect(Collectors.toList());
            invInboundBillItem.setnPrice(result.get(0).getnPrice());
            invInboundBillItem.setvProjectNo(buyPurchaseBill.getvProjectNo());
            invInboundBillItem.setvProjectDec(buyPurchaseBill.getvProjectDec());
            invInboundBillItem.setvSpaName(item.getvSpaName());
            invInboundBillItem.setvSpaModel(item.getvSpaModel());
            invInboundBillItem.setvSpaBrand(item.getvSpaBrand());
            invInboundBillItem.setnQty(item.getnQty());
            invInboundBillItem.setvArriveNo(item.getvArriveNo());
            invInboundBillItem.setvBuyNo(item.getvBuyNo());
            invInboundBillItem.setvContractNo(item.getvContractNo());
            //这里处理一下手填的库位编号
            invInboundBillItem = this.getWHInfo(invInboundBillItem,item.getvLocationNo());
            invInboundBillItem.setCreateBy(commonService.getUsername());//合同号
            invInboundBillItem.setCreateTime(DateUtils.getNowDate());
            this.invInboundBillItemMapper.insertInvInboundBillItem(invInboundBillItem);

            //再更新已入库数量
            if (result.get(0).getnINWHQty() == null){
                result.get(0).setnINWHQty(item.getnQty());
            }else{
                result.get(0).setnINWHQty(item.getnQty().add(result.get(0).getnINWHQty()));
            }
            result.get(0).setUpdateBy(commonService.getUsername());
            result.get(0).setUpdateTime(DateUtils.getNowDate());
            this.buyPurchaseBillItemMapper.updateBuyPurchaseBillItem(result.get(0));

            //反查明细
            InvInboundBillItem searchItem = new InvInboundBillItem();
            searchItem.setnMainId(nMainId);
            List<InvInboundBillItem> listResult = this.invInboundBillItemMapper.selectInvInboundBillItemList(searchItem);
            // 更改库存
            commonService.changeInventory(list.get(0), new ArrayList<>(listResult),"IN");

            //最后修改到货明细状态
            InvArriveInfoItem arriveInfoItem = this.invArriveInfoItemMapper.selectInvArriveInfoItemById(item.getId());
            arriveInfoItem.setvInBoundBillNo(vBillNo);
            arriveInfoItem.setStatus("1");//已入库
            arriveInfoItem.setUpdateBy(commonService.getUsername());
            arriveInfoItem.setUpdateTime(DateUtils.getNowDate());
            this.invArriveInfoItemMapper.updateInvArriveInfoItem(arriveInfoItem);
        }

        return 1;
    }

    @Override
    public List<Inv0014Data> searchInList(Inv0014Data param) {
        return invArriveInfoItemMapper.searchInList(param);
    }

    private InvInboundBillItem getWHInfo(InvInboundBillItem invInboundBillItem,String vLocationNo) throws Exception {
        InvWarehouseInfo invWarehouseInfo = new InvWarehouseInfo();
        invWarehouseInfo.setvWHCode(vLocationNo);
        List<InvWarehouseInfo> invWarehouseInfos = this.invWarehouseInfoMapper.selectInvWarehouseInfoList(invWarehouseInfo);
        if (invWarehouseInfos.isEmpty()){
            throw new Exception("不存在"+vLocationNo+"库位,请确认");
        }
        else{
            invInboundBillItem.setvLocationId(String.valueOf(invWarehouseInfos.get(0).getId()));
            invInboundBillItem.setvAreaId(String.valueOf(invWarehouseInfos.get(0).getParentId()));
            invWarehouseInfo = this.invWarehouseInfoMapper.selectInvWarehouseInfoById(invWarehouseInfos.get(0).getParentId());
            invInboundBillItem.setvWHId(String.valueOf(invWarehouseInfo.getParentId()));
        }
        return invInboundBillItem;
    }
}
